'use strict';
const db = uniCloud.database();
// 获取 `user` 集合的引用
const collection = db.collection('events');
const signin = db.collection('signin');
var $ = db.command.aggregate
exports.main = async (event, context) => {
	let {
		name
	} = event
	let res = {}
	switch (event.action) {
		case 'save':
			if (event.id) {
				res = await collection.doc(event.id).set(event)
			} else {
				res = await collection.add(event)
			}

			break
		case 'list':
			res = await collection.orderBy("create_date", "desc").get()
			break
		case 'view':
			res = await collection.where({
				_id: event.id
			}).get()
			break
		case 'viewAll11':
			var artRes = await collection.where({
				_id: event.id
			}).get()
			var signRes = await signin.where({
				event_id: event.id
			}).get()
			artRes.signList = signRes
			res = artRes
			break
		case 'signlist':
			// res = await signin.where({
			// 	event_id: event.id
			// }).get()
			res = await signin.aggregate()
				.match({
					event_id: event.id
				})
				.lookup({
					from: 'uni-id-users',
					localField: 'user_id',
					foreignField: '_id',
					as: 'signList',
				})
				// .replaceRoot({
				// 	newRoot: $.mergeObjects([$.arrayElemAt(['$signList', 0]), '$$ROOT'])
				// })
				.addFields({
					username: $.arrayElemAt(['$signList.username', 0])
				})
				.project({
					signList: 0
				})
				.sort({
					sign_date: -1
				})
				.end()
			break
	}
	// let res = await collection.add({
	//         name
	//     })
	// //返回数据给客户端
	// console.log('res : ', res)
	return res
};
